package com.lancoo.znbkxx.teacher.aibkTestCoach.auidoPlayer;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.lancoo.znbkxx.teacher.R;
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast;
import com.lancoo.znbkxx.teacher.utils.ToastUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class SubChildVoicePlayer implements OnBufferingUpdateListener, OnCompletionListener,
        OnPreparedListener, DefaultLifecycleObserver {

    public MediaPlayer mediaPlayer; // 媒体播放器
    private final SeekBar seekBar; // 拖动条
    private final String musicUrl;
    private final ImageView ivPlay;
    private Timer mTimer;
    // 计时器
    private TimerTask timerTask;

    public boolean isPrepare() {
        return isPrepare;
    }

    public void setPrepare(boolean prepare) {
        isPrepare = prepare;
    }

    private boolean isPrepare = false;

    private boolean palyClick = false;
    private boolean isSeekBackStart = true;//是否在播放结束后重置播放进度

    private PlayListener playListener;

    // 初始化播放器
    public SubChildVoicePlayer(final Context context, SeekBar seekBar, final String musicUrl, ImageView ivPlay, boolean isSeekBackStart, final PlayListener playListener) {
        super();
        this.seekBar = seekBar;
        this.musicUrl = musicUrl;
        this.ivPlay = ivPlay;
        this.isSeekBackStart = isSeekBackStart;
        ivPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取当前图片ConstantState类对象
                Drawable.ConstantState t1 = ivPlay.getDrawable().getCurrent().getConstantState();
                //找到需要比较的图片ConstantState类对象
                Drawable.ConstantState t2 = context.getDrawable(R.mipmap.ic_music_loading).getConstantState();
                if (t1.equals(t2)) {
                    return;
                } else {
                    ivPlay.setImageResource(R.drawable.music_loading);
                    if (isPrepare) {
                        playListener.onStartPlay();
                    } else {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                playUrl(musicUrl);
                            }
                        }).start();
                    }
                }
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBarChangeEvent());
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 设置媒体流类型
            mediaPlayer.setOnBufferingUpdateListener(this);
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        startTime();
        this.seekBar.setEnabled(false);

        this.playListener = playListener;

    }

    private void startTime() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new TimerTask() {

                @Override
                public void run() {
                    if (mediaPlayer == null)
                        return;
                    if (mediaPlayer.isPlaying() && !seekBar.isPressed()) {
                        handler.sendEmptyMessage(0); // 发送消息
                    }
                }
            };
            // 每一秒触发一次
            mTimer.schedule(timerTask, 0, 50);
        }
    }


    private final Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mediaPlayer != null) { //避免出现空指针异常
                int position = mediaPlayer.getCurrentPosition();
                int duration = mediaPlayer.getDuration();
                switch (msg.what) {
                    case 0:
                        if (duration > 0) {
                            // 计算进度（获取进度条最大刻度*当前音乐播放位置 / 当前音乐时长）
                            long pos = seekBar.getMax() * position / duration;
                            seekBar.setProgress((int) pos);
                        }

                        break;
                    case 1:
                        MyToast.INSTANCE.showToast("音频地址出错，无法获取音频资源");
                        break;
                    case 2://隔1.5秒秒跳转到开始出 免得显示突兀
                        seekBar.setProgress(0);
                        ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
                        break;
                }
            }
        }

    };


    public void play() {
        palyClick = true;
        if (isPrepare) {
            if (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                ivPlay.setImageResource(R.mipmap.icon_subchild_music_pause);
            } else {
                pause();
            }
        }


    }

    public void rePlay() {
        mediaPlayer.seekTo(0);
        seekBar.setProgress(0);
        ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
    }

    /**
     * @param url url地址
     */
    private void playUrl(String url) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(url); // 设置数据源
            mediaPlayer.prepare(); // prepare自动播放
            mediaPlayer.start();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    ivPlay.setImageResource(R.mipmap.icon_subchild_music_pause);
                }
            });
            playListener.initFirstPlay();
        } catch (IllegalArgumentException | SecurityException | IOException | IllegalStateException e) {
            e.printStackTrace();
            //handler.sendEmptyMessage(1);
        }

    }

    // 暂停
    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
            mediaPlayer.pause();
        }
    }

    // 停止
    public void stop() {
        ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        pause();
    }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) {
        pause();
    }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        pause();
    }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) {
        pause();
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
        isPrepare = true;
        mediaPlayer.seekTo(0);
        seekBar.setProgress(0);
        setPrepare(true);
        seekBar.setEnabled(false);
//        if (palyClick){
//            play();
//        }

    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        seekBar.setProgress(seekBar.getMax());
        if (isSeekBackStart) {
            handler.sendEmptyMessageDelayed(2, 1500);
        }

        ivPlay.setImageResource(R.mipmap.icon_subchild_music_play);
        playListener.onFinishPlay();
    }

    public interface PlayListener {
        void onFinishPlay();

        void onStartPlay();

        void initFirstPlay();
    }

    /**
     * 缓冲更新
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
    }

    private class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            this.progress = progress * mediaPlayer.getDuration()
                    / seekBar.getMax();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.seekTo(progress);
        }
    }

}